const COS = require('cos-nodejs-sdk-v5');
const {
  COS: { SecretId, SecretKey, Protocol, Assets },
} = require('../../project.config');

const cos = new COS({
  SecretId,
  SecretKey,
  Protocol, // 请求协议： 'https:' 或 'http:'
});

const _upload = function (filename, stream) {
  return new Promise((resolve, reject) => {
    cos.putObject(
      {
        Bucket: Assets.Bucket /* Bucket,名称 必须 */,
        Region: Assets.Region /* 所属地域 必须 */,
        Key: filename /* 必须 */,
        Body: stream, // 上传文件对象
      },
      function (err, data) {
        if (data) {
          resolve('https://' + data.Location);
        } else {
          reject(err);
        }
      }
    );
  });
};

module.exports = _upload;
